﻿//This script use a link   http://Shawnvision7264.gotoip55.com/AddResp.php   to connect a mysql database on web to fetch some datas.
//This 


using UnityEngine;
using System.Collections;
using System;
using System.IO;


public class ConnectWeb : MonoBehaviour {



	//public  string urlStr="http://127.0.0.1/phpdemos/AddResp.php";
	public  string urlStr="http://Shawnvision7264.gotoip55.com/AddResp.php";

	string paraStr="paraStr";
	int m_bItemReady = 0;
	string WebRetStr=string.Empty;
	public string devName=string.Empty;
	bool enableEncriptionCoverFlag=true;  // false for that the database is full, so we display the cover obj
	public GameObject coverObj;

	// Use this for initialization
	void Start () {
		string lParaStr=PlayerPrefs.GetString(paraStr);
		//Debug.Log("Current ParaStr: "+lParaStr);
		//Debug.Log("Current ParaStr len:  "+ lParaStr.Length);
		if((lParaStr==null)||(lParaStr==string.Empty)||(lParaStr.Length<=1))   //Means it is the 1st time to generate this string , we need to upload and check the uuid
		{
			Debug.Log("Local Para string not exist.  Check on web");
			devName=Guid.NewGuid().ToString();
			StartCoroutine("RequestDevSignal");
		}
		else
		{
			if(lParaStr=="Full")
			{
				enableEncriptionCoverFlag=false;
				Debug.LogWarning("The installed devices is outnumbered");
			}
			else
			{
				devName=PlayerPrefs.GetString(paraStr);
				StartCoroutine("RequestDevSignal");
				enableEncriptionCoverFlag=true;
				//Debug.LogWarning("The installed devices is outnumbered");
			}

		}


	}
	
	// Update is called once per frame
	void Update () {


		if(!enableEncriptionCoverFlag)
		{
			if(coverObj.activeSelf==false)
			{
				coverObj.SetActive(true);
			}		

		}
	
//		if(Input.GetKeyDown(KeyCode.A))
//		{
//
//			StartCoroutine("RequestDevSignal");
//
//			Guid tmpGuid=Guid.NewGuid();
//			Debug.Log(tmpGuid.ToString());
//
//		}

	}



	//IEnumerator RequestDevSignal(string url, string devName){
	
	IEnumerator RequestDevSignal(){
       
		m_bItemReady = 0;
		string ldevName="\""+devName+"\"";
		ldevName = System.Uri.EscapeDataString(ldevName);

		Debug.Log("converted ldevname: "+ldevName);
		string sendUrl=urlStr+"?"+"Name"+"="+ldevName;

//		Uri uri =new Uri(sendUrl);
		Debug.Log(sendUrl);

		WWW web;
		web = new WWW(sendUrl);
		yield return web;
		
		if (web.isDone && (web.error == null)){	
			//print("&&&&&&&&&&&&& bytes str: " + web.text);
			
			if (!string.IsNullOrEmpty(web.text)){

				WebRetStr=web.text;
				if(WebRetStr.Contains("F"))
				{
					enableEncriptionCoverFlag=false;
					PlayerPrefs.SetString(paraStr,"Full");
				}
				if((WebRetStr.Contains("I")))
				{
					enableEncriptionCoverFlag=true;
					PlayerPrefs.SetString(paraStr,devName);
				}

				Debug.Log("Get return string: "+WebRetStr);

			}

		}

	} 


}
